﻿using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using WebApplication1.classes.Core.Chrome.Bookmarks.Wrapper;
using WebApplication1.classes.Core.JSTree;

namespace WebApplication1.classes.dataSources {
    public class BookmarkDatasource {
    
        private Bookmarks dataset_;
        public String filePath{get;set;}

        public BookmarkDatasource(){
            dataset_ = null;
        }

        public void deserialize(){
            dataset_ = null;
            if (String.IsNullOrEmpty(filePath)){
                return;
            }
            using ( var sr = new StreamReader( filePath ) ) {
                String output = sr.ReadToEnd();
                var jsonSerializerSettings = new JsonSerializerSettings();
                jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                dataset_ = JsonConvert.DeserializeObject<Bookmarks>( output, jsonSerializerSettings );
            }
        }

        private void parseBookmarkIntoJsTreeNode(Bookmark bookmark, JsTreeNode node){
            foreach ( Bookmark childBookmark  in bookmark.childrenToList() ) {
                var childJsTreeNode = new JsTreeNode(childBookmark.name);
                node.children.Add(childJsTreeNode);
                childJsTreeNode.attr.id = childBookmark.uniqueIdentifier;
                parseBookmarkIntoJsTreeNode(childBookmark,childJsTreeNode);
            }
        }

        public IList<Bookmark> bookmarkParentListForItemPath(string itemPath){
            return dataset_.parentsForUniqueKey( itemPath);
        }

        public IList<Bookmark> bookmarkChildListForItemPath(string itemPath){
            return dataset_.childrenForUniqueKey(itemPath);
        }

        public string bookmarkJsTreeForItemPath(string id){
/*
            var jsonConverter = new JavaScriptSerializer();
            jsonConverter.RegisterConverters(new JavaScriptConverter[]{new BookmarkJsonConverter()});
            result = jsonConverter.Serialize(bookmarks_);
*/

            string result = null;
            var jsTree = new JsTree();

            
            IList<Bookmark> list = dataset_.childrenForUniqueKey(id);
            foreach(var item in list){
                var node = new JsTreeNode(item.name);
                node.attr.id = item.uniqueIdentifier;
                parseBookmarkIntoJsTreeNode(item,node);
                jsTree.data.Add(node);
            }

            
            result = jsTree.data.jsonString();
            return String.Format("{0}",result);
        }

    }
}